const util = require('../../../utils/util.js');
const http = util.http;

Page({
  data: {
    isEdit: false,
    shop_id: '',
    shopParts: [],
    params: {
      page: 1,
      pageSize: 10
    }
  },
  // 开始编辑
  handleEditReplacement: function () {
    this.setData({
      isEdit: true
    })
  },
  // 编辑完成
  handleDoneReplacement: function () {
    this.setData({
      isEdit: false
    })
  },
  // 减少设备数量
  handleReduce: function (e) {
    let that = this;
    let id = e.target.dataset.id;
    let index = this.getNumberById(id);
    let params = {
      parts_id: id
    };
    console.log(index);
    if (this.data.shopParts[index].surplus_num > 1 ) {
      
      http('/parts/editShopParts', 'post', params)
      .then(() => {
        let val = --that.data.shopParts[index].surplus_num;
        let data = that.data.shopParts;
        this.setData({
          shopParts: data
        });
      })
    } else {
      wx.showModal({
        title: '删除备件',
        content: '您将删除该备件，确定吗？',
        cancelText: '取消',
        confirmText: '确认',
        success: function () {
          http('/parts/delShopParts', 'post', params)
            .then((data) => {
              let newList = that.data.shopParts.filter((item) => item.id != id);
              that.setData({
                shopParts: newList
              })
            })
        }
      })
    }
    
  },
  // 删除设备
  deleteDevice: function (e) {
    let id = e.target.dataset.id;
    let params = {
      parts_id: id
    };
    let that = this;
    wx.showModal({
      title: '删除备件',
      content: '您将删除该备件，确定吗？',
      cancelText: '取消',
      confirmText: '确认',
      success: function () {
        http('/parts/delShopParts', 'post', params)
        .then((data) => {
          let newList = that.data.shopParts.filter((item) => item.id != id);
          that.setData({
            shopParts: newList
          })
        })
      }
    })
  },
  onLoad: function (options) {
    var id = options.id;
    this.setData({
      shop_id: id
    });
    const params = {
      shop_id: id,
      page: 1,
      pageSize: 10
    }
    http('/parts/myShopParts', 'post', params)
    .then((data) => {
      console.log(data);
      this.setData({
        shopParts: data.list
      });
    });
  },
  // 下触底加载
  onReachBottom: function () {
    const params = this.data.params;
    params.page++;
    params.shop_id = this.data.shop_id;
    http('/parts/myShopParts', 'post', params)
      .then((data) => {
        console.log(data.list);
        let shopParts = this.data.shopParts.concat(data.list);
        console.log(shopParts);
        this.setData({
          shopParts: shopParts
        });
      });
  },
  // 工具函数，通过id获取数据里面的对象number的值 [{id: 1,number: 0}]
  getNumberById: function (id) {
    let index;
    let target = this.data.shopParts.forEach((item, i) => {
      if (item.id == id) {
        index = i;
      }
    });
    return index;
  },
})
